import { defineStore } from 'pinia';
import { getPrivilegeList, logout } from '@/api/login';
import { strToJson } from '@/utils/util';
import type { IPrivilege } from '@/types';
import { generator } from '@/router/router.config';
import type { RouteRecordRaw } from 'vue-router';

export const ACCESS_TOKEN = 'token';

const getPrivilege = (privilegeStr?: string | null) => {
  if (privilegeStr) {
    return strToJson<IPrivilege>(privilegeStr) || {};
  }
  return {};
};

// 登录接口中：user_name 或 email
const loginName = sessionStorage.getItem('loginName') || '';

// 处理用户登录、登出、个人信息、权限路由
export default defineStore('user', {
  state: () => {
    return {
      token: sessionStorage.getItem(ACCESS_TOKEN) || '',
      // id: userInfo.id,
      // // 头像
      // avatar: userInfo.avatar,
      // 角色(鉴权)
      role: sessionStorage.getItem('role') || '',
      // 菜单权限
      privilege: getPrivilege(sessionStorage.getItem('privilege')),
      // 菜单
      menus: [] as RouteRecordRaw[],
      // 菜单
      routes: [] as RouteRecordRaw[],
      // 登录接口中：user_name 或 email
      loginName,
    };
  },
  actions: {
    // 设置loginName
    setLoginName(loginName: string) {
      this.loginName = loginName;
      sessionStorage.setItem('loginName', loginName);
    },
    // 设置token
    setToken(token: string) {
      this.token = token;
      sessionStorage.setItem(ACCESS_TOKEN, token);
    },
    setRole(role: string) {
      this.role = role;
      sessionStorage.setItem('role', role);
    },
    async setPrivilege(privilege: string) {
      if (privilege === 'all') {
        const res = await getPrivilegeList();
        this.privilege = getPrivilege(res.data.privilege);
        sessionStorage.setItem('privilege', res.data.privilege);
      } else {
        this.privilege = getPrivilege(privilege);
        sessionStorage.setItem('privilege', privilege);
      }
    },
    // 用户退出登录
    clearState() {
      sessionStorage.removeItem('role');
      sessionStorage.removeItem(ACCESS_TOKEN);
      sessionStorage.removeItem('privilege');
    },
    // 获取菜单
    setMenu() {
      const { menus, routes } = generator(this.privilege, this.role);
      this.menus = markRaw(menus);
      this.routes = markRaw(routes);
    },
    async logout() {
      await logout();
      this.clearState();
      return true;
    },
  },
});
